//index.js
//获取应用实例
const app = getApp()

var apiHost = wx.getStorageSync('apiHost');
var yunId  = wx.getStorageSync('yunId');
var openId  = wx.getStorageSync('openId');

Page({

    /**
     * 设置全局变量，以便后期动态加载
     */
    detailList : [],    //初始化店铺详情

    goodslist: [],      //初始化商品list

    data: {
      shopState: "休息中",
      feekbackState : "",
      hiddenLoading: true,    //loading
      feekbackListCon : [],
      currentTab : '0',
      indicatorDots: false,
      autoplay: true,
      interval: 2500,
      duration: 1000,
      cateGorylist: '',   //初始化店铺分类list
      showModalA: false,
    },

    //  页面初始化加载使用的方法
    onLoad: function (options) {
        var that = this;
        //显示加载动画
        that.setData({
            hiddenLoading: false
        });
        that.shopShopDetail();              //初始化店铺详情
        that.initHeght();                   //初始化页面高度
        that.shopGoodsCategory();           //初始化店铺分类
        // that.feekbackList(that.data.feekbackState);   //初始化店铺评价

        /**
         * 获取系统信息
         */
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    winWidth: res.windowWidth,
                    winHeight: res.windowHeight,
                    hiddenLoading: true
                });
            }
        });

    },
    initHeght:function () {
        var that = this;
        /*获取指定元素高度*/
        var query = wx.createSelectorQuery();
        var shopHeight = "";
        //获取店铺头部高度
        query.select('#shop').boundingClientRect()
        query.exec(function (res) {
            shopHeight = res[0].height;

            wx.getSystemInfo({
                success: function (res) {
                    that.setData({
                        SwBoxHeight:res.windowHeight-shopHeight
                    });
                }
            });
        });
    },
    //获取店铺详情
    shopShopDetail:function(){
        var that = this;

        //获取店铺详情
        wx.request({
            url: apiHost+"xcx/store/detail",
            data: {
                yunId : yunId  //测试云店主id
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              var shopStateFlag = '';
              var code = res.data.code;
              var msg = res.data.msg

              if (code="10000"){
                if (res.data.data.state=="1"){
                  shopStateFlag="营业中"
                }else{
                  shopStateFlag = "休息中"
                }
                that.setData({
                  detailList: res.data.data,
                  shopState: shopStateFlag
                })
              }else{
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 2000,
                  mask: true
                });
              }

            },
        });
    },
    /**
     * 店铺分类
     */
    shopGoodsCategory:function () {
        var that = this;
        // 初始化加载店铺分类信息
        wx.request({
            url: apiHost+"xcx/category/list",
            data: {
                yunId : yunId  //测试云店主id
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              var code = res.data.code;
              var msg = res.data.msg

              if (code == "10000") {
                that.shopCateIdGoods(res.data.data[0].id);//初始化分类，第一个分类下的商品
                that.setData({
                  categoryId: res.data.data[0].id,
                  cateGorylist: res.data.data

                })
              }else{
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 2000,
                  mask: true
                });
              }

            },
        });
    },
    /**
     * 分类下的商品
     * @param cateGoryId
     */
    shopCateIdGoods:function (cateGoryId) {
        var that = this;
        //显示加载动画
        that.setData({
          hiddenLoading: false
        });
        // 微信请求（点击分类）
        wx.request({
            url: apiHost+"xcx/goods/list/condition",
            data: {

                categoryId:cateGoryId,
                yunId : yunId
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              var code = res.data.code;
              var msg = res.data.msg

              if (code == "10000") {
                that.setData({
                  goodslist: res.data.data.list,
                  hiddenLoading: true
                })
              }else{
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 2000,
                  mask: true
                });
              }

            },
        });
    },
    //单击改变分栏的显示状态
    backgroundClick: function (e) {
        var that = this;
        var categoryId= e.target.dataset.toggle; //获取点击分类框的id
        //设置分类id
        that.setData({
            categoryId: categoryId
        });
        that.shopCateIdGoods(categoryId);//点击显示分类下对应的商品
    },
    //搜索商品
    search_btn: function () {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
      wx.navigateTo({
        url: '../searchShopGoods/searchShopGoods'
      });
    },
    /**
     * 获取商品评价列表
     * @param state 评价状态
     */
    feekbackList:function(state){

        var that = this;
        wx.request({
            url: apiHost+"xcx/goods/feedback/list",
            data: {
                yunId : yunId,
                state : state
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              var code = res.data.code;
              var msg = res.data.msg

              if (code == "10000") {
                that.countfeekbackHeight(); //初始化评价高度
                that.setData({
                  feekbackListCon: res.data.data.list
                })
              }else{
                wx.showToast({
                  title: msg,
                  icon: 'none',
                  duration: 2000,
                  mask: true
                });
              }
                

            },
        });
    },
    //评价点击事件
    feekbackClick :function (e) {
        var that = this;
        var feekbackState= e.target.dataset.toggle;

        that.setData({
            feekbackState: feekbackState
        })
        that.feekbackList(feekbackState);
    },
    //计算评价列表高度
    countfeekbackHeight:function () {
        var that = this;
        /*获取指定元素高度*/

        var query2 = wx.createSelectorQuery();

        var shopHeight = "";



        query2.select('#shop').boundingClientRect()
        query2.exec(function (res) {
            shopHeight = res[0].height;

            wx.getSystemInfo({
                success: function (res) {
                    that.setData({
                        evaluateHeight:res.windowHeight-shopHeight
                    });
                }
            });
        });
    },
    /**
     * 计算商品设置高度
     */
    countShopSetUpHeight:function () {
        var that = this;

        that.shopShopDetail();      //初始化店铺详情

        /*获取指定元素高度*/
        var that = this;
        /*获取指定元素高度*/
        var query = wx.createSelectorQuery();
        var shopHeight = "";
        //获取店铺头部高度
        query.select('#shop').boundingClientRect()
        query.exec(function (res) {
            shopHeight = res[0].height;
            wx.getSystemInfo({
                success: function (res) {
                    that.setData({
                        shopSetUpHeight:res.windowHeight-shopHeight+30
                    });
                }
            });
        });
    },
    /**
     ** 滑动切换tab
     */
    bindChange: function (e) {
        var that = this;
        var cateGorytab = 0;    //店铺商品+分类 tab
        var feekbacTab = 1;     //店铺评价 tab
        var shopSetUptab = 2;   //店铺   tab
        var currIndex = e.target.dataset.current; //获取当前tab页数

        //  重新设置tab 页数
        that.setData({ currentTab: e.detail.current });

        if(currIndex==cateGorytab){
            that.shopGoodsCategory();   //初始化店铺分类
        }else if(currIndex==feekbacTab){
         
            that.feekbackList(that.data.feekbackState);        //初始化店铺评价
        }else if(currIndex==shopSetUptab){
            that.countShopSetUpHeight();//初始化店铺设置高度
        }
    },
      /**
       * 点击tab切换
       */
    swichNav: function (e) {
        var that = this;

       

        var cateGorytab = 0;    //店铺商品+分类 tab
        var feekbacTab = 1;     //店铺评价 tab
        var shopSetUptab = 2;   //店铺   tab
        var currIndex = e.target.dataset.current  //获取当前tab页数


        if (this.data.currentTab === e.target.dataset.current) {
            return false;
        } else {
            if(currIndex==cateGorytab){
                that.shopGoodsCategory();   //初始化店铺分类
            }else if(currIndex==feekbacTab){
                that.feekbackList(that.data.feekbackState);        //初始化店铺评价
            }else if(currIndex==shopSetUptab){
                that.countShopSetUpHeight();//初始化店铺设置高度
            }
        }
          //  重新设置tab 页数
          that.setData({
              currentTab: e.target.dataset.current
          });
     },
    //店铺状态开启按钮
    switch2Change: function (e) {

        var that = this;

        var shopStateFlag_open = "1";   //店铺开启状态
        var shopStateFlag_close = "0";  //店铺关闭状态

        // 判断是否打开
        if (e.detail.value){
            that.shopStateSetUp(shopStateFlag_open);    //修改店铺状态开启
            that.setData({ shopState: "营业中" });

        }else{
            that.shopStateSetUp(shopStateFlag_close);    //修改店铺状态开启
            that.setData({ shopState: "休息中" });
        }
    },
    /**
     * 店铺状态修改
     * @param cateGoryId
     */
    shopStateSetUp:function (state) {

        var that = this;

        //显示加载动画
        that.setData({
            hiddenLoading: false
        });

        // 微信请求（点击分类）
        wx.request({
            url: apiHost+"xcx/store/edit",
            data: {
                openId : openId,
                yunId : yunId,
                state : state
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                that.setData({
                    currentTab: 2,
                    hiddenLoading: true        //隐藏loading
                });
                that.countShopSetUpHeight();//初始化店铺设置高度
            },
        });
    },
    //跳转店铺设置
    shopSetUp : function(){
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
        wx.navigateTo({
            url: '../shopSetUp/shopSetUp'
        });
    },

    //跳转店铺订单
    orders: function () {
      var flag = "";
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
      wx.navigateTo({
        url: '../order/order?flag=' + flag
      });
    },

    //跳转分类管理
    categoryManage: function () {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
      wx.navigateTo({
        url: '../categoryManage/categoryManage'
      });
    },
    //添加商品
    addGoods : function (e) {
      var that = this;
      var detailLists = that.data.detailList
      if (detailLists.name==''){

        that.setData({
          msg:'请先进入店铺完善相关信息',
          showModalA: true        //隐藏loading
        });
        
      }else{
        wx.showToast({
          title: '加载中',
          icon: 'loading',
          mask: true
        })
        wx.navigateTo({
          url: '../goods/goods'
        });
      }

    },
    /**
     * 修改商品
     */
    updateGoods : function(e){
      var spuId = e.target.dataset.toggle;

      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
      wx.navigateTo({
        url: '../goods/goods?spuId=' + spuId
      });
    },
    /**
     * 跳转预警商品
     */
    thresholdGoods : function(e){
        var spuId = e.target.dataset.toggle;
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            mask: true
        })
        wx.navigateTo({
            url: '../thresholdGoods/thresholdGoods'
        });
    },
    /**
* 跳转预警商品
*/
    toYunShopIndex: function (e) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
      wx.navigateTo({
        url: '../yunShopIndex/yunShopIndex'
      });
    },
    /**
     * 跳转下架商品
     */
    downGoods : function(e){
        var spuId = e.target.dataset.toggle;
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            mask: true
        })
        wx.navigateTo({
            url: '../downGoods/downGoods'
        });
    },

    //点击商品，弹出商品详情
    goodsDetail: function (e) {
      var that = this;

      var spuId = e.currentTarget.dataset.toggle;

      console.log(spuId)

      that.alertDetail(spuId);//获取弹出商品详情

      that.setData({
        showModal: true,
      })
    },
    /**
     * 获取弹出商品详情
     */
    alertDetail: function (spuId) {
      var that = this;
      wx.request({
        url: apiHost + "/xcx/goods/alert/detail",
        data: {
          openId: openId,
          yunId: yunId,
          spuId: spuId
        },
        header: {
          "Content-Type": "application/json"
        },
        success: function (res) {
          var code = res.data.code;
          var msg = res.data.msg

          if (code == "10000") {
            var GodDetail = res.data.data
            that.setData({
              goodsDetails: GodDetail,
              goodsDetails_num: GodDetail.shopCartCount
            })
          }else{
            wx.showToast({
              title: msg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        }
      })
    },
    /**
    * 隐藏模态对话框
    */
    hideModal: function () {
      this.setData({
        showModal: false
      });
    },

    /**
    * 隐藏模态对话框
    */
    hideModalA: function () {
      this.setData({
        showModalA: false
      });
    },
    /**
  * 用户点击右上角分享
  */
    onShareAppMessage: function (options) {

      var that = this;
      var goodsDetails = that.data.goodsDetails;

      // 设置菜单中的转发按钮触发转发事件时的转发内容
      var shareObj = {
        title: goodsDetails.name,
        // desc: '最具人气的小程序开发联盟!',
        path: 'pages/index/index?spuId=' + goodsDetails.spuId,
        success: function (res) {
          // 转发成功之后的回调
          if (res.errMsg == 'shareAppMessage:ok') {
            console.log("转发成功之后的回调")
          }
        },
        fail: function (res) {
          // 转发失败之后的回调
          if (res.errMsg == 'shareAppMessage:fail cancel') {
            console.log("用户取消转发")
          } else if (res.errMsg == 'shareAppMessage:fail') {
            console.log("转发失败")
          }
        },
      }
      // 来自页面内的按钮的转发
      if (options.from == 'button') {
        // 此处可以修改 shareObj 中的内容
        shareObj.path = 'pages/index/index?spuId=' + goodsDetails.spuId;
      }
      // 返回shareObj
      return shareObj;
    }

})
